import pymysql


class DBTools:

    @classmethod
    def __get_conn(cls):
        # 创建连接
        conn = pymysql.connect(host="211.103.136.244", port=7061,
                               user='student', password='iHRM_student_2022',
                               database='ihrm', charset='utf8')
        return conn

    @classmethod
    def get_noe(cls, sql):
        """获取单条查询数据"""
        conn = None
        cursor = None
        res = None
        try:
            # 获取连接对象
            conn = cls.__get_conn()
            # 创建游标
            cursor = conn.cursor()
            # 执行sql语句
            cursor.execute(sql)
            # 返回结果(fetchone查询返回一条数据, fetchall查询所有)
            res = cursor.fetchall()
        except Exception as e:
            print(e)
        finally:
            #  关闭游标
            conn.close()
            #  关闭连接
            cursor.close()
            return res

    @classmethod
    def uid_db(cls, sql):
        """增删改操作"""
        conn = None
        cursor = None
        try:
            # 获取连接对象
            conn = cls.__get_conn()
            # 创建游标
            cursor = conn.cursor()
            # 执行sql语句
            cursor.execute(sql)
            # 提交事务
            conn.commit()
        except Exception as e:
            print(e)
            # 回滚
            conn.rollback()
        finally:
            #  关闭游标
            conn.cursor()
            #  关闭连接
            cursor.close()
